<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

// 用户数据
const tableData = ref([])
const loading = ref(false)

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  name: '',
  username: '',
  email: '',
  role: null,
  isDeleted: null
})

// 获取用户列表
const getUserList = async () => {
  try {
    loading.value = true
    
    // 构建查询参数，过滤空值
    const params = {}
    
    if (searchForm.name) params.name = searchForm.name
    if (searchForm.username) params.username = searchForm.username
    if (searchForm.email) params.email = searchForm.email
    if (searchForm.role !== null && searchForm.role !== '') params.role = searchForm.role
    if (searchForm.isDeleted !== null && searchForm.isDeleted !== '') params.isDeleted = searchForm.isDeleted
    
    console.log('搜索参数:', params)
    
    const response = await request.get(`/user/selectByPage/${pagination.currentPage}/${pagination.pageSize}`, { 
      params: params
    })
    
    console.log('响应数据:', response)
    
    // 处理响应数据
    let data = response
    
    if (response && response.data !== undefined) {
      data = response.data
    }
    
    // 获取记录数组
    let records = []
    let total = 0
    
    if (Array.isArray(data)) {
      records = data
      total = data.length
    } else if (data && typeof data === 'object') {
      records = data.records || data.data || data.list || data.items || []
      total = data.total || data.totalCount || data.size || records.length
    }
    
    if (Array.isArray(records) && records.length > 0) {
      // 处理数据映射
      tableData.value = records.map(item => ({
        uid: item.uid,
        name: item.name,
        number: item.number,
        username: item.username,
        email: item.email,
        role: item.role,
        scorenum: item.scorenum,
        icon: item.icon,
        // 处理 is_deleted 字段映射
        isDeleted: item.is_deleted !== undefined ? item.is_deleted : item.isDeleted
      }))
      
      pagination.total = total
      console.log(`获取到 ${records.length} 条数据`)
    } else {
      tableData.value = []
      pagination.total = 0
      ElMessage.info('未找到匹配的数据')
    }
  } catch (error) {
    console.error('请求错误:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 删除用户
const removeDataById = async (uid) => { 
  try {
    await ElMessageBox.confirm('确定要删除这个用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.delete("/user/remove", { params: { uid }})
    if (response.code === 200 || response.status === 200) {
      ElMessage.success(response.message || '删除成功')
      getUserList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 修改用户
const updateDataById = async (user) => { 
  try {
    ElMessage.info(`修改用户: ${user.name} - 功能待实现`)
    // 这里应该弹出编辑对话框
  } catch (error) {
    ElMessage.error('修改失败')
  }
}

// 查看用户详情
const viewUserDetail = (user) => {
  ElMessage.info(`查看用户: ${user.name} (ID: ${user.uid})`)
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.username = ''
  searchForm.email = ''
  searchForm.role = null
  searchForm.isDeleted = null
  pagination.currentPage = 1
  getUserList()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  getUserList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getUserList()
}

// 生命周期钩子
onMounted(() => {
  getUserList()
})
</script>

<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="姓名">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入姓名" 
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="用户名">
            <el-input 
              v-model="searchForm.username" 
              placeholder="请输入用户名" 
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input 
              v-model="searchForm.email" 
              placeholder="请输入邮箱" 
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="角色">
            <el-select 
              v-model="searchForm.role" 
              placeholder="选择角色" 
              clearable
            >
              <el-option label="全部" :value="null" />
              <el-option label="管理员" :value="0" />
              <el-option label="学生" :value="1" />
              <el-option label="教师" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.isDeleted" 
              placeholder="选择状态" 
              clearable
            >
              <el-option label="全部" :value="null" />
              <el-option label="未注销" :value="0" />
              <el-option label="已注销" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 用户表格区域 -->
    <div class="table-section">
      <el-card class="table-card">
        <template #header>
          <div class="table-header">
            <span class="table-title">用户列表</span>
            <div class="table-actions">
              <el-button type="primary" size="small" @click="getUserList">刷新</el-button>
            </div>
          </div>
        </template>

        <el-table 
          :data="tableData" 
          style="width: 100%" 
          v-loading="loading"
          stripe
          empty-text="暂无数据"
          class="user-table"
        >
          <el-table-column 
            prop="uid" 
            label="用户ID" 
            width="80"
            align="center"
          />
          <el-table-column 
            prop="name" 
            label="姓名" 
            width="120"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.name || '-' }}
            </template>
          </el-table-column>
          <el-table-column 
            prop="number" 
            label="编号" 
            width="120"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.number || '-' }}
            </template>
          </el-table-column>
          <el-table-column 
            prop="username" 
            label="用户名" 
            width="150"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.username || '-' }}
            </template>
          </el-table-column>
          <el-table-column 
            prop="email" 
            label="邮箱"
            min-width="180"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.email || '-' }}
            </template>
          </el-table-column>
          <el-table-column 
            prop="role" 
            label="角色" 
            width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag v-if="scope.row.role === 0" type="danger" size="small">
                管理员
              </el-tag>
              <el-tag v-else-if="scope.row.role === 1" type="primary" size="small">
                学生
              </el-tag>
              <el-tag v-else-if="scope.row.role === 2" type="success" size="small">
                教师
              </el-tag>
              <el-tag v-else type="info" size="small">
                未知
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column 
            prop="scorenum" 
            label="积分" 
            width="100"
            align="center"
          >
            <template #default="scope">
              <span>{{ scope.row.scorenum || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column 
            prop="isDeleted" 
            label="状态" 
            width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag v-if="scope.row.isDeleted == 0" type="success" size="small">
                未注销
              </el-tag>
              <el-tag v-else-if="scope.row.isDeleted == 1" type="info" size="small">
                已注销
              </el-tag>
              <el-tag v-else type="warning" size="small">
                未知
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column 
            label="操作" 
            width="200" 
            fixed="right"
            align="center"
          >
            <template #default="scope">
              <el-button 
                size="small" 
                @click="viewUserDetail(scope.row)"
              >
                查看
              </el-button>
              <el-button 
                size="small" 
                type="primary" 
                @click="updateDataById(scope.row)"
              >
                修改
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="removeDataById(scope.row.uid)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            :background="true"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-form .el-form-item {
  margin-right: 16px;
  margin-bottom: 16px;
}

.search-buttons {
  margin-left: auto;
}

/* 表格区域样式 */
.table-section {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.user-table {
  border-radius: 4px;
  overflow: hidden;
}

.user-table ::v-deep(.el-table__header) {
  background-color: #f5f7fa;
}

.user-table ::v-deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 16px 0 0 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form .el-form-item {
    margin-right: 12px;
  }
}

@media (max-width: 992px) {
  .user-management {
    padding: 16px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .search-buttons {
    margin-left: 0;
    display: flex;
    justify-content: flex-end;
  }
}

@media (max-width: 768px) {
  .user-management {
    padding: 12px;
  }
  
  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .pagination-section {
    justify-content: center;
  }
  
  .pagination-section ::v-deep(.el-pagination) {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>